var ns, bmLocation, trans, WXPhotoPicker;
app = new Vue({
    el: '#app',
    data: {
        form: {
            pageindex: 0,
            pagesize: 10,
            // status: 1, // 1-任务列表 2-新增记录
            PlanType: 1,
            TaskStatus: 0//0-未开始,1-进行中,2-已结束

        },
        newform: {
            PlanType: 1,
            EncriptID: '',
            DeviceID: 0,
            DeviceName: '',
            DeviceLocationPlace: '',
            DeviceNo: '',
            ModelNo: '',
            ProjectID: 0,
            ProjectName: '',
            CheckTime: '',
            InChargeManName: '',
            ProcessContent: '',
            CheckStatus: 1,
            TaskCompleteContent: '',
            GPSLocation: '',
            IsAllowUpload: false
        },
        standardlist: [],
        imglist: [],
        ProjectList: [],
        projectSelected: 0,
        maxuploadcount: CONFIG.maxuploadcount,
        IsAllowWatermark: false,
        //首页-手动添加
        IsHome:false,
    },
    methods: {
        do_choose_device: function () {
            var that = this;
            if (that.IsHome) {
                return;
            }
            ns.openWin('equipment_devicelist_frm', '选择设备', {
                projectid: that.newform.ProjectID
            });
        },
        do_save: function () {
            var that = this;
            if (that.newform.DeviceID <= 0) {
                api.toast({
                    msg: '请选择设备',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.IsAllowUpload && that.imglist.length == 0) {
                api.toast({
                    msg: '请上传图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.CheckStatus == 2) { //异常
                api.confirm({
                    title: '提示',
                    msg: '当前结果异常,是否需要进行报事报修登记?',
                    buttons: ['报事报修', '直接完成']
                }, function (ret, err) {
                    var ServiceStatus = -1;
                    if (ret.buttonIndex == 1) {
                        ServiceStatus = 1;
                    } else if (ret.buttonIndex == 2) {
                        ServiceStatus = 0;
                    }
                    if (ServiceStatus >= 0) {
                        that.do_save_process(ServiceStatus);
                    }
                });
                return;
            }
            that.do_save_process(0);
        },
        do_save_process: function (ServiceStatus) {
            var that = this;
            var options = {};
            options.action = "saveequipmenttaskdevicedata";
            options.DeviceID = that.newform.DeviceID;
            options.PlanType = that.newform.PlanType;
            options.standardlist = JSON.stringify(that.standardlist);
            options.CheckStatus = that.newform.CheckStatus;
            options.GPSLocation = that.newform.GPSLocation;
            options.ServiceStatus = ServiceStatus;
            options.TaskCompleteContent = that.newform.TaskCompleteContent;
            var filelist = [];
            for (var i = 0; i < that.imglist.length; i++) {
                if (that.imglist[i].isupload) {
                    filelist.push(that.imglist[i].url);
                }
            }
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    api.sendEvent({
                        name: 'reloadhomedetail',
                    });
                    api.toast({
                        msg: '操作成功',
                        duration: 2000,
                        location: 'bottom'
                    });
                    setTimeout(function () {
                        api.closeWin();
                    }, 500)
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true,
                files: {
                    file: filelist
                }
            });
        },
        select_active: function (item, CheckStatus) {
            var that = this;
            item.CheckStatus = CheckStatus;
            var isallnormal = true;
            for (var i = 0; i < that.standardlist.length; i++) {
                if (that.standardlist[i].CheckStatus == 2) {
                    isallnormal = false;
                }
            }
            if (isallnormal) {
                this.newform.CheckStatus = 1;
            } else {
                this.newform.CheckStatus = 2;
            }
        },
        select_all_active: function (CheckStatus) {
            var that = this;
            that.newform.CheckStatus = CheckStatus;
            if (that.newform.CheckStatus == 1) {
                for (var i = 0; i < that.standardlist.length; i++) {
                    that.standardlist[i].CheckStatus = CheckStatus;
                }
            }   
        },
        choose_picture: function () {
            var that = this;
            ns.confirmPer('camera', function () {
                if (that.IsAllowWatermark) {
                    that.upload_choose_picture();
                }
                else {
                    that.choose_picture_start();
                }
            })
        },
        choose_picture_start: function () {
            var that = this;
            if (that.imglist.length >= that.maxuploadcount) {
                api.toast({
                    msg: '最多支持' + that.maxuploadcount + '张图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            api.actionSheet({
                cancelTitle: '取消',
                buttons: ['拍照', '从相册选择']
            }, function (ret, err) {
                //拍照
                if (ret.buttonIndex == 1) {
                    that.upload_choose_picture();
                    return;
                }
                //从相册选择
                if (ret.buttonIndex == 2) {
                    that.choose_picture_album();
                    return;
                }
                //取消 
                else {
                    return false;
                }
            });
        },
        choose_picture_album: function () {
            var that = this;
            WXPhotoPicker.open({
                max: that.maxuploadcount - that.imglist.length,
                type:'image',
            }, function (ret) {
                if (ret) {
                    if (ret.list.length > 0) {
                        ret.list.forEach((item) => {
                            that.do_imageFilter(item.path);
                            // that.imglist.push({
                            //     ID: 0,
                            //     url: item.path,
                            //     thumbPath: item.path,
                            //     isupload: true
                            // });
                        });
                    }
                }
            });
        },
        remove_img: function (index, item) {
            var that = this;
            that.imglist.splice(index, 1);
            if (item.ID > 0) {
                that.do_remove_uploadimg(item);
            }
        },
        do_remove_uploadimg: function (item) {
            var that = this;
            var options = {
                action: 'doremoveproductimg',
                ID: item.ID,
            }
            ns.post(options, function (succeed, data, err) { });
        },
        StartBmap: function () {
            var that = this;
            ns.confirmPer('location', function () {
                that.StartLocation();
            })
        },
        StartLocation: function () {
            var that = this;
            var num = 0; //次数
            that.newform.GPSLocation = '';
            bmLocation.stopLocation();
            bmLocation.singleLocation({
                reGeocode: true,
                netWorkState: true
            }, function (ret) {
                if (ret.status) {
                    var locationDescribe = ns.DealLocationDescribe(ret.reGeo.locationDescribe);
                    that.newform.GPSLocation = ret.reGeo.province + ret.reGeo.city +
                        ret.reGeo.district + ret.reGeo.street + ret.reGeo.streetNumber + locationDescribe;
                    // if (ret.reGeo.poiList != undefined && ret.reGeo.poiList.length > 0) {
                    //     that.newform.GPSLocation = ret.reGeo.province + ret.reGeo.city +
                    //         ret.reGeo.district + ret.reGeo.street + ret.reGeo.poiList[0].name;
                    // }
                }
            });
        },
        configManager: function () {
            bmLocation.configManager({
                // accuracy: 'hight_accuracy',
                filter: 1,
                activityType: 'automotiveNavigation',
                coordinateType: 'BMK09LL',
                locationTimeout: 10,
                reGeocodeTimeout: 10
            });
            // bmLocation.configManager({
            //     accuracy: 'device_sensors',
            //     filter: 1,
            //     activityType:'automotiveNavigation',
            //     coordinateType:'GCJ02',
            //     locationTimeout: 10,
            //     reGeocodeTimeout: 10
            // });
        },
        do_viewimages: function (activeIndex) {
            var that = this;
            var imageUrls = [];
            for (var i = 0; i < that.imglist.length; i++) {
                imageUrls.push(that.imglist[i].url);
            }
            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                activeIndex: activeIndex,
                imageUrls: imageUrls
            });
        },
        get_standard_data: function () {
            var that = this;
            if (that.newform.DeviceID <= 0 && that.newform.EncriptID == '') {
                return;
            }
            var options = {};
            options.action = "getdevicestandardlist";
            options.DeviceID = that.newform.DeviceID;
            options.EncriptID = that.newform.EncriptID;
            options.PlanType = that.newform.PlanType;
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    that.standardlist = data.list;
                    that.newform.CheckTime = data.CheckTime;
                    that.newform.InChargeManName = data.InChargeManName;
                    if (that.newform.EncriptID != '') {
                        that.newform.DeviceID = data.DeviceID;
                        that.newform.DeviceName = data.DeviceName;
                        that.newform.ProjectID = data.ProjectID;
                        that.newform.ProjectName = data.ProjectName;
                        that.newform.DeviceNo = data.DeviceNo;
                        that.newform.ModelNo = data.ModelNo;
                        that.newform.DeviceLocationPlace = data.DeviceLocationPlace;
                        that.getIsAllowWatermark();//获取是否只调用相机权限
                    }
                    that.newform.EncriptID = '';
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true
            });
        },
        do_select_plantype: function (type) {
            this.newform.PlanType = type;
            this.get_standard_data();
        },
        do_choose_project: function () {
            var that = this;
            ns.openWin('chooseprojectlist_frm', '选择项目', {
                projectlevel: 1,
            });
        },
        get_select_project: function (data) {
            var that = this;
            that.newform.ProjectID = data.projectid;
            that.newform.ProjectName = data.name;
            that.getIsAllowWatermark();//获取是否只调用相机权限
        },
        get_project_list: function () {
            var that = this;
            var options = {
                action: 'getmytopprojectlist'
            };
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    that.ProjectList = data.list;
                    that.newform.ProjectID = that.ProjectList[0].ID;
                    that.newform.ProjectName = that.ProjectList[0].Name;
                    that.initPicker();//加载下拉列表数据
                    that.getIsAllowWatermark();//获取是否只调用相机权限
                }
            });
        },
        do_selectProject: function () {
            var that = this;
            that.newform.DeviceName = '';
            that.newform.DeviceNo = '';
            that.newform.ModelNo = '';
            that.newform.DeviceLocationPlace = '';
        },
        initPicker: function () {
            var _this = this;
            (function ($, doc) {
                $.init();
                $.ready(function () {
                    // 选择项目
                    var pickerProject = new $.PopPicker({
                        layer: 1,
                        fileID: 'ID',
                        fileName: 'Name',
                    });
                    var projectData = _this.ProjectList || [];
                    pickerProject.setData(projectData);
                    var showProjectPickerButton = doc.getElementById('chooseproject');
                    showProjectPickerButton.addEventListener('click', function (event) {
                        pickerProject.show(function (items) {
                            if (_this.newform.ProjectID != items[0].value) {
                                _this.newform.DeviceID = 0;
                                _this.newform.DeviceName = '';
                                _this.newform.IsAllowUpload = false;
                                _this.newform.DeviceNo = '';
                                _this.newform.ModelNo = '';
                                _this.newform.DeviceLocationPlace = '';
                                _this.standardlist = [];
                            }
                            _this.newform.ProjectID = items[0].value;
                            _this.newform.ProjectName = items[0].text;
                            _this.getIsAllowWatermark();//获取是否只调用相机权限
                            //返回 false 可以阻止选择框的关闭
                            //return false;
                        });
                    }, false);
                });
            })(mui, document);
        },
        //获取是否只调用相机权限
        getIsAllowWatermark: function () {
            var that = this;
            if (!that.newform.ProjectID) {
                return;
            }
            var options = {
                action: 'getplanparam',
                ProjectID: that.newform.ProjectID,
                ConfigKey: 'SBGLPhotoUse'
            };
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    that.IsAllowWatermark = data.type == 2 ? true : false;
                }
            });
        },
        // 系统只调用相机 并添加水印
        upload_choose_picture: function () {
            var that = this;
            api.getPicture({
                sourceType: 'camera',
                encodingType: 'jpg',
                destinationType: 'url',
                allowEdit: false,
                saveToPhotoAlbum: that.IsAllowWatermark ? false : true,
            }, function (ret, err) {
                if (ret && ret.data) {
                    that.do_imageFilter(ret.data);
                    // if (that.IsAllowWatermark) {
                    //     that.waterMark(ret.data);
                    //     return;
                    // }
                    // else {
                    //     that.imglist.push({
                    //         ID: 0,
                    //         url: ret.data,
                    //         thumbPath: ret.data,
                    //         isupload: true
                    //     });
                    // }
                }
            });
        },
        waterMark: function (imagePath) {
            var that = this;
            if (!imagePath) {
                api.toast({
                    msg: '图片地址为空',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            var imageName = imagePath.split('/').pop(); //获取图片名称
            var dateTime = moment().format('YYYY-MM-DD HH:mm:ss');
            // 调用生成水印方法  返回Base64图片格式
            ns.setWatermark(imagePath, '设备管理水印', dateTime, that.newform.GPSLocation).then((value) => {
                var base64Str = value;
                if (base64Str) {
                    //Base64图片 转jpg、png格式
                    trans.saveImage({
                        base64Str: base64Str,
                        // album:true,
                        imgPath: "fs://watermark/",
                        imgName: imageName
                    }, function (ret, err) {
                        if (ret.status) {
                            var newImagePath = api.fsDir + '/' + 'watermark' + '/' + imageName;
                            that.imglist.push({
                                ID: 0,
                                url: newImagePath,
                                thumbPath: newImagePath,
                                isupload: true
                            });
                            //水印图片-保存到相册
                            api.saveMediaToAlbum({
                                path: 'fs://watermark/' + imageName
                            }, function (ret, err) {
                            });
                        } else {
                            api.toast({
                                msg: '水印图片保存本地失败！',
                                duration: 2000,
                                location: 'bottom'
                            });
                            return;
                        }
                    });
                } else {
                    // api.toast({
                    //     msg: '生成水印失败！',
                    //     duration: 2000,
                    //     location: 'bottom'
                    // });
                    that.imglist.push({
                        ID: 0,
                        url: imagePath,
                        thumbPath: imagePath,
                        isupload: true
                    });
                    return;
                }
            })
        },
        //图片压缩
        do_imageFilter:function(path){
            var that=this;
            var imgName = Date.now() + '.jpg';
            var target_w = 500;
            var imageFilter = api.require('imageFilter');
            imageFilter.getAttr({
                path: path
            }, function(ret, err) {
                if (ret.status) {
                    if (ret.width < target_w) {
                        target_w = ret.width;
                    }
                    var original_w = ret.width;
                    var original_h = ret.height;
                    var scale = original_w / target_w;
                    var target_h = Math.round(original_h / scale);
                    imageFilter.compress({
                        img: path,
                        quality: 1,
                        size: {
                            w: target_w,
                            h: target_h
                        },
                        save: {
                            album: false,
                            imgPath: api.cacheDir + '/upload/',
                            imgName: imgName
                        }
                    }, function(ret, err) {
                        if (ret.status) {
                            var imgFullName=api.cacheDir + '/upload/' + imgName;
                            if (that.IsAllowWatermark) {
                                that.waterMark(imgFullName);
                                return;
                            }
                            else {
                                that.imglist.push({
                                    ID: 0,
                                    url: imgFullName,
                                    thumbPath: imgFullName,
                                    isupload: true
                                });
                            }
                        }else{
                            alert( JSON.stringify( err ) );
                        }
                    });
                }
            });
        },
        getDeviceData(){
            var that=this;
            if(!that.newform.ProjectID){
                return;
            }
            var options = {};
            options.action = "getequipmentdevicelist";
            options.pagesize = 100000000;
            options.pageindex = 0;
            options.keywords = "";
            options.ProjectID = that.newform.ProjectID;
            ns.post(options, function(succeed, data, err) {
                if (succeed) {
                    var list=data.list;
                    if(list!=undefined&&list.length>0){
                        var result=list.filter((item)=>{
                            return item.ID==that.newform.DeviceID;
                        });
                        if(result.length>0){
                            that.newform.DeviceName = result[0].DeviceName;
                            that.newform.ProjectName = result[0].ProjectName;
                            that.newform.IsAllowUpload = result[0].IsAllowUpload;
                            that.newform.DeviceNo = result[0].DeviceNo;
                            that.newform.ModelNo = result[0].ModelNo;
                            that.newform.DeviceLocationPlace = result[0].DeviceLocationPlace;
                            that.get_standard_data();
                        }
                    }
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },
    },

});
apiready = function () {
    api.parseTapmode();
    ns = window.Foresight.Util;
    WXPhotoPicker = api.require('WXPhotoPicker');
    bmLocation = api.require('bmLocation');
    trans = api.require('trans');
    app.newform.EncriptID = api.pageParam.EncriptID || '';
    //首页跳转
    app.IsHome= api.pageParam.IsHome || false;
    var homeDeviceID=api.pageParam.DeviceID || '';
    var homeProjectID=api.pageParam.projectid || '';
    var homeProjectName=api.pageParam.name || '';
    if(app.IsHome){
        app.newform.DeviceID = homeDeviceID;
        app.newform.ProjectID = homeProjectID;
        app.newform.ProjectName = homeProjectName;
        app.getIsAllowWatermark();//获取是否只调用相机权限
        app.getDeviceData();
    }
    else{
        app.get_project_list();
    }
    api.addEventListener({
        name: 'do_choose_device_done'
    }, function (ret, err) {
        app.newform.DeviceID = ret.value.id;
        app.newform.DeviceName = ret.value.name;
        app.newform.ProjectName = ret.value.projectname;
        app.newform.IsAllowUpload = ret.value.IsAllowUpload;
        app.newform.DeviceNo = ret.value.DeviceNo;
        app.newform.ModelNo = ret.value.ModelNo;
        app.newform.DeviceLocationPlace = ret.value.DeviceLocationPlace;
        app.get_standard_data();
    });
    setTimeout(function () {
        if (app.newform.EncriptID != '') {
            app.get_standard_data();
        }
    }, 500)
    setTimeout(function () {
        app.configManager();
        app.StartBmap();
    }, 1000)
    app.get_select_project(api.pageParam);
    api.addEventListener({
        name: 'do_choose_project_complete'
    }, function (ret) {
        app.get_select_project(ret.value);
    })
    bmLocation.setAgreePrivacy({
        agree: true
    });

    //是否开启GPS定位服务(暂仅支持Android)
    // bmLocation.isGPSEnable(function(ret) {
    //     api.alert({
    //             msg: JSON.stringify(ret)
    //         })
    // });
};

